package com.kefu.chat.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.time.Duration;
import java.time.Instant;
import java.util.List;
import java.util.Objects;

import com.kefu.chat.vo.ChatUserParam;
import com.kefu.common.exception.BusinessException;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class BaiDuAsrUtil {

    public static ChatUserParam.TransferVideoR transferVideo(String audioPath) {
        Instant now = Instant.now();
        ChatUserParam.TransferVideoR result = new ChatUserParam.TransferVideoR();
        result.setStartTime(System.currentTimeMillis());
        try {
            BaiDuBceToken holder = new BaiDuBceToken("8IFuzjT6fGV359HSo5dXVyCF", "QsDvPWxIvxu2heEb1sbZ5AIYLw6CRamo", "audio_voice_assistant_get");
            holder.resfresh();
            String token = holder.getToken();
            String resultMsg = null;
            boolean METHOD_RAW = true; // 默认以json方式上传音频文件
            if (METHOD_RAW) {
                resultMsg = runRawPostMethod(token, audioPath);
            } else {
                resultMsg = runJsonPostMethod(token, audioPath);
            }
            if (StrUtil.isNotBlank(resultMsg)) {
                JSONObject resultJson = new JSONObject(resultMsg);
                log.info("百度语音转义返回信息 : {}", resultJson.toString());
                if (resultJson.containsKey("result")) {
                    String tmp = resultJson.getStr("result");
                    if (StrUtil.isNotBlank(tmp)) {
                        JSONArray array = new JSONArray(tmp);
                        if (Objects.nonNull(array)) {
                            List<String> tmpList = array.toList(String.class);
                            if (Objects.nonNull(tmpList)) {
                                result.setResult(String.join("", tmpList));
                            }
                        }
                    }
                }
                result.setEndTime(System.currentTimeMillis());
                return result;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            log.info("百度语音转文字耗时 : {}", Duration.between(now, Instant.now()).toMillis());
        }
        return result;
    }

    private static String runRawPostMethod(String token, String audioPath) throws IOException, BusinessException {
        String url2 = "http://vop.baidu.com/server_api" + "?cuid=" + ConnUtil.urlEncode("1234567JAVA") + "&dev_pid=" + 1537 + "&token=" + token;
        //测试自训练平台需要打开以下信息
        //String url2 = URL + "?cuid=" + ConnUtil.urlEncode(CUID) + "&dev_pid=" + DEV_PID + "&lm_id="+ LM_ID + "&token=" + token;
        String contentTypeStr = "audio/" + audioPath.substring(audioPath.length() - 3) + "; rate=" + 8000;
        //System.out.println(url2);
        byte[] content = getFileContent(audioPath);
        HttpURLConnection conn = (HttpURLConnection) new URL(url2).openConnection();
        conn.setConnectTimeout(5000);
        conn.setRequestProperty("Content-Type", contentTypeStr);
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        conn.getOutputStream().write(content);
        conn.getOutputStream().close();
        log.info("url is " + url2);
        log.info("header is  " + "Content-Type :" + contentTypeStr);
        String result = ConnUtil.getResponseString(conn);
        return result;
    }

    static String runJsonPostMethod(String token, String audioPath) throws BusinessException, IOException {
        byte[] content = getFileContent(audioPath);
        String speech = base64Encode(content);
        JSONObject params = new JSONObject();
        params.put("dev_pid", 1537);
        //params.put("lm_id",LM_ID);//测试自训练平台需要打开注释
        params.put("format", audioPath.substring(audioPath.length() - 3));
        params.put("rate", 8000);
        params.put("token", token);
        params.put("cuid", "1234567JAVA");
        params.put("channel", "1");
        params.put("len", content.length);
        params.put("speech", speech);

        // System.out.println(params.toString());
        HttpURLConnection conn = (HttpURLConnection) new URL("http://vop.baidu.com/server_api").openConnection();
        conn.setConnectTimeout(5000);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
        conn.setDoOutput(true);
        conn.getOutputStream().write(params.toString().getBytes());
        conn.getOutputStream().close();
        String result = ConnUtil.getResponseString(conn);


        params.put("speech", "base64Encode(getFileContent(FILENAME))");
        log.info("url is : " + "http://vop.baidu.com/server_api");
        log.info("params is :" + params.toString());


        return result;
    }

    static byte[] getFileContent(String filename) throws BusinessException, IOException {
        File file = new File(filename);
        if (!file.canRead()) {
            System.err.println("文件不存在或者不可读: " + file.getAbsolutePath());
            throw new BusinessException("file cannot read: " + file.getAbsolutePath());
        }
        FileInputStream is = null;
        try {
            is = new FileInputStream(file);
            return ConnUtil.getInputStreamContent(is);
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    static String base64Encode(byte[] content) {
        /**
         Base64.Encoder encoder = Base64.getEncoder(); // JDK 1.8  推荐方法
         String str = encoder.encodeToString(content);
         **/

        char[] chars = Base64Util.encode(content); // 1.7 及以下，不推荐，请自行跟换相关库
        String str = new String(chars);

        return str;
    }
}
